package com.usernet.product.web.action;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.usernet.product.comm.BaseAction;
import com.usernet.product.entity.Admin;
import com.usernet.product.entity.LoginError;
import com.usernet.product.utils.LogConstants;
import com.usernet.product.utils.Page;
import com.usernet.product.utils.PageResult;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;
import com.usernet.product.web.form.AdminForm;

public class AdminAction extends BaseAction {

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String loginName = request.getParameter("loginName");
		String password = ProductUtils.getMD5String(request
				.getParameter("password"));
		int ret = adminDao.login(loginName, password);
		if (ret == -1) {
			request.setAttribute("error", "用户名不存在");
			return mapping.findForward("error");
		} else if (ret == -2) {
			// 错误次数验证
			String ip = ProductUtils.getIpAddr(request);
			LoginError loginError = loginErrorDao.getByParam(loginName, ip,
					ProductConfig.LOGIN_FLAG_MANAGE);
			if (loginError != null
					&& loginError.getCount() >= ProductConfig.MAX_LOGIN_ERROR_COUNT) {
				// 锁定用户
				adminDao.lockUser(loginName);
				request.setAttribute("error", "密码错误"
						+ ProductConfig.MAX_LOGIN_ERROR_COUNT + "次,帐号被锁定");
				return mapping.findForward("error");
			} else {
				int count = 1;
				if (loginError != null) {
					loginError.setCount(loginError.getCount() + 1);
					count = loginError.getCount();
					loginError
							.setTime(new Timestamp(System.currentTimeMillis()));
					loginErrorDao.modify(loginError);
				} else {
					loginError = new LoginError();
					loginError.setLoginName(loginName);
					loginError.setIp(ip);
					loginError.setFlag(ProductConfig.LOGIN_FLAG_MANAGE);
					loginError.setCount(1);
					loginError.setStatus(0);
					loginError
							.setTime(new Timestamp(System.currentTimeMillis()));
					loginErrorDao.save(loginError);
				}
				request.setAttribute("error", "密码错误" + count + "次");
				return mapping.findForward("error");
			}
		} else if (ret == -3) {
			request.setAttribute("error", "用户状态不可用");
			return mapping.findForward("error");
		} else {
			// 清除错误登录信息
			loginErrorDao.cleanLoginError(loginName,
					ProductConfig.LOGIN_FLAG_MANAGE);
			Admin admin = (Admin) adminDao.getById(Admin.class, ret);
			// 添加日志
			ProductUtils.addAdminLog(request, loginName, LogConstants.login,
					null);
			request.getSession().setAttribute("admin", admin);

		}
		return mapping.findForward("success");
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		// 添加日志
		ProductUtils.addAdminLog(request, admin.getLoginName(),
				LogConstants.logout, null);
		request.getSession().removeAttribute("admin");

		return mapping.findForward("logout");
	}

	public ActionForward toHome(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int param = Integer.parseInt(request.getParameter("home"));
		ActionForward action = null;
		switch (param) {
		case 0:
			action = new ActionForward("/software.do?method=toList");
			break;
		case 1:
			action = new ActionForward("/type.do?method=toList");
			break;
		case 2:
			action = new ActionForward("/comment.do?method=toList");
			break;
		case 3:
			action = new ActionForward("/error.do?method=toList");
			break;
		case 4:
			action = new ActionForward("/photo.do?method=toList");
			break;
		case 5:
			action = new ActionForward("/user.do?method=toList");
			break;
		case 6:
			action = new ActionForward("/backup.do?method=toList");
			break;
		case 7:
			action = new ActionForward("/log.do?method=toList");
			break;
		case 8:
			action = new ActionForward("/admin.do?method=toPassword");
			break;
		case 9:
			action = new ActionForward("/admin.do?method=toList");
			break;
		case 10:
			action = new ActionForward("/resource.do?method=toList");
			break;
		case 11:
			action = new ActionForward("/adminLog.do?method=toList");
			break;
		}
		return action;
	}

	public ActionForward toList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		AdminForm mForm = (AdminForm) form;

		PageResult<Admin> result = null;
		Page page = new Page();
		// 分页信息
		String pageNo = mForm.getPageNo();
		String pageSize = mForm.getPageSize();
		if (pageSize != null) {
			page.setEveryPage(Integer.parseInt(pageSize.trim()));
		}
		if (pageNo != null) {
			page.setCurrentPage(Integer.parseInt(pageNo.trim()));
		}

		result = adminDao.getAllByPage(page);
		request.setAttribute("form", mForm);
		request.setAttribute("list", result.getContent());
		request.setAttribute("page", result.getPage());
		request.setAttribute("size", result.getSize());

		return mapping.findForward("list");
	}

	public ActionForward toPassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		return mapping.findForward("password");
	}

	/** 修改密码 */
	public ActionForward doPassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		String password1 = request.getParameter("password");
		String password2 = request.getParameter("password1");
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		if (!admin.getPassword().equals(ProductUtils.getMD5String(password1))) {
			request.setAttribute("msg", "原密码不正确");
			request.setAttribute("return", "admin.do?method=toPassword");
			return mapping.findForward("admin_msg");
		} else {
			admin.setPassword(ProductUtils.getMD5String(password2));
			if (adminDao.modify(admin)) {
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.update_password, new Object[] {
								admin.getId(), admin.getLoginName() }), null);
				request.getSession().setAttribute("admin", admin);
				request.setAttribute("msg", "修改成功");
				request.setAttribute("return", "admin.do?method=toPassword");
				return mapping.findForward("admin_msg");
			} else {
				request.setAttribute("msg", "修改失败");
				request.setAttribute("return", "admin.do?method=toPassword");
				return mapping.findForward("admin_msg");
			}
		}
	}

	/** 删除用户 */
	public ActionForward doDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Admin admin = (Admin) adminDao.getById(Admin.class, id);
		if (adminDao.delete(admin)) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.delete_manager, new Object[] {
							admin.getId(), admin.getLoginName() }), null);
			return mapping.findForward("other");
		} else {
			request.setAttribute("msg", "删除失败");
			request.setAttribute("return", "admin.do?method=toList");
			return mapping.findForward("admin_msg");
		}
	}

	/** to添加用户 */
	public ActionForward toAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		return mapping.findForward("add");
	}

	/** to修改用户 */
	public ActionForward toUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Admin admin = (Admin) adminDao.getById(Admin.class, id);
		request.setAttribute("admin", admin);
		return mapping.findForward("update");
	}

	/** 添加用户 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String loginName = request.getParameter("loginName").trim();
		boolean bool = adminDao.checkLoginName(loginName);
		if (bool) {
			request.setAttribute("msg", "登录名已经存在");
			request.setAttribute("return", "admin.do?method=toAdd");
			return mapping.findForward("admin_msg");
		}
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		int flag = Integer.parseInt(request.getParameter("flag"));
		Admin admin = new Admin();
		admin.setLoginName(loginName);
		admin.setPassword(ProductUtils.getMD5String(password));
		admin.setEmail(email);
		admin.setStatus(0);
		admin.setFlag(flag);
		admin.setTime(new Timestamp(System.currentTimeMillis()));
		int id = adminDao.save(admin);
		if (id > 0) {
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.add_manager, new Object[] { id,
							admin.getLoginName() }), null);
			request.setAttribute("msg", "添加成功");
		} else {
			request.setAttribute("msg", "添加失败");

		}
		request.setAttribute("return", "admin.do?method=toList");
		return mapping.findForward("admin_msg");
	}

	/** 修改用户 */
	public ActionForward doUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		int flag = Integer.parseInt(request.getParameter("flag"));
		Admin admin = (Admin) adminDao.getById(Admin.class, id);
		admin.setPassword(ProductUtils.getMD5String(password));
		admin.setEmail(email);
		admin.setFlag(flag);
		if (adminDao.modify(admin)) {
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.update_manager, new Object[] {
							admin.getId(), admin.getLoginName() }), null);
			request.setAttribute("msg", "修改成功");
		} else {
			request.setAttribute("msg", "修改失败");

		}
		request.setAttribute("return", "admin.do?method=toList");
		return mapping.findForward("admin_msg");
	}

	/*
	 * 锁定用户
	 */
	public ActionForward doCancle(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int userId = Integer.parseInt(request.getParameter("id"));
		Admin admin = (Admin) adminDao.getById(Admin.class, userId);
		admin.setStatus(1);// 不可用
		if (adminDao.modify(admin)) {
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.lock_manager, new Object[] {
							admin.getId(), admin.getLoginName() }), null);
		}
		return mapping.findForward("other");
	}

	/*
	 * 解锁用户
	 */
	public ActionForward doOk(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int userId = Integer.parseInt(request.getParameter("id"));
		Admin admin = (Admin) adminDao.getById(Admin.class, userId);
		admin.setStatus(0);// 解锁
		if (adminDao.modify(admin)) {
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.unlock_manager, new Object[] {
							admin.getId(), admin.getLoginName() }), null);
		}
		return mapping.findForward("other");
	}
}
